package com.hhd.pdf.components.dict;

import com.hhd.pdf.CommonUtils;
import com.hhd.pdf.components.AbstractInLineBlockComponent;
import com.hhd.pdf.context.GeneratorContext;
import com.hhd.pdf.variable.DynamicFormula;
import com.hhd.pdf.variable.VariableContext;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Phrase;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

@Component
public class DictComponent extends AbstractInLineBlockComponent {

    @Autowired
    List<DictParser> parserList;

    @Override
    public List<Element> createElements(org.dom4j.Element element,
                                        GeneratorContext context,
                                        VariableContext rootVariableContext) throws DocumentException, IOException {
        DictParser dictParser = getDictParser(element);


        Object formulaValue = getFormulaValue(element, rootVariableContext);

        String value = dictParser.parseDict(formulaValue);

        Phrase phrase = new Phrase(value, context.getGeneratorParameters().getFont());

        return CommonUtils.newList(phrase);
    }

    private DictParser getDictParser(org.dom4j.Element element) {
        String dictParserName = element.attributeValue("dictParser");
        if (CommonUtils.isEmpty(dictParserName)) dictParserName = "default";
        for (DictParser dictParser : parserList) {
            if (dictParser.getDictParserName().equals(dictParserName)) {
                return dictParser;
            }
        }
        throw new RuntimeException("没有找到数据字典解析器: " + dictParserName);
    }

    private static Object getFormulaValue(org.dom4j.Element element, VariableContext rootVariableContext) {
        String valueFormula = element.attributeValue("value");
        DynamicFormula<Object> formula = DynamicFormula.formula(valueFormula, Object.class);
        rootVariableContext.execute(formula);

        Object formulaValue = formula.getFormulaValue();
        return formulaValue;
    }

    @Override
    public String getName() {
        return "dict";
    }
}
